#!/bin/bash

set -eu -o pipefail

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
proto_dir="${SCRIPT_DIR}"/../generated_types/protos

usage() {
  echo "usage: $0 { types | decode <message_type> | encode <message_type> }"
  exit 1
}

protoc() {
  # bash 3.x (default on macos big-sur 🤦) has no readarray.
  while IFS= read -r line; do
    proto_flags+=("$line")
  done < <(find  "${proto_dir}" -name '*.proto')

  command protoc -I"${proto_dir}" "${proto_flags[@]}" "$@"
}

types() {
  while read -r proto <&3; do
    pkg=$(grep '^package' "${proto}" | sed 's/package \(.*\);.*/\1/')
    while read -r message <&4; do
      echo "${pkg}.${message}"
    done 4< <(grep '^message ' "${proto}" | sed 's/message \(.*\) {.*/\1/')
  done 3< <(find "${proto_dir}" -name '*.proto')
}

decode() {
  if [ -z "${1:-}" ]; then
    echo >&2 "WARNING: Pass a message type to render field names. Command '$0 types' lists valid types."
    echo >&2
    command protoc --decode_raw
  else
    protoc --decode="$1"
  fi
}

encode() {
  if [ -z "${1:-}" ]; then
    usage
  fi
  protoc --encode="$1"
}

case $1 in
  types)
    shift
    types "$@"
  ;;
  decode)
    shift
    decode "$@"
  ;;
  encode)
    shift
    encode "$@"
  ;;
  *)
  usage
  ;;
esac
